package com.design.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.common.JsonResult;
import com.design.sys.entity.Role;
import com.design.sys.entity.User;
import com.design.sys.service.IRoleService;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.validation.constraints.Min;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang
 * @since 2023-06-09
 */
@Api(value="Role Controller")
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @GetMapping("/getlist")
    public JsonResult<?> getRoleListPage(@RequestParam(value = "roleName", required = false) String roleName,
                                         @RequestParam("pageNo") @Min(value = 1, message = "页码必须大于等于1") Long pageNo,
                                         @RequestParam("pageSize") Long pageSize) {

        //解决查询项为空不能点击无法查询的bug
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper();
        wrapper.eq(!StringUtils.isNullOrEmpty(roleName), Role::getRoleName, roleName);
        //按照userId降序排序
        wrapper.orderByDesc(Role::getRoleId);
        //计算总页数
        Page<Role> page = new Page<>(pageNo, pageSize);
        roleService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return JsonResult.success(data);
    }
    @PostMapping
    public JsonResult<?> addRole(@RequestBody Role role){
        roleService.addRole(role);
        return JsonResult.success("新增角色成功");
    }
    @PutMapping()
    public JsonResult<?> updateRole(@RequestBody Role role){
        roleService.updateRoleById(role);
        return JsonResult.success("修改角色成功");
    }
    @GetMapping("/{id}")
    public JsonResult<?> getRoleById(@PathVariable("id") Integer id){
        Role role = roleService.getRoleById(id);
        return JsonResult.success(role);
    }

    @DeleteMapping("/{id}")
    public JsonResult<?> deleteRoleById(@PathVariable("id") Integer id){
        //物理删除
        roleService.deleteRoleById(id);
        return JsonResult.success("删除角色成功");
    }

    @GetMapping("/all")
    public JsonResult<List<Role>> getAllRole(){
        List<Role> roleList = roleService.list();
        return JsonResult.success(roleList);
    }


}
